package com.example.w.service.impl;

import com.example.w.common.exception.SystemException;
import com.example.w.common.pojo.Table;
import com.example.w.dao.TableDao;
import com.example.w.service.TableManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class TableManagerServiceImpl implements TableManagerService {

    @Autowired
    private TableDao tableDao;

    @Override
    //添加新餐桌
    public Integer addTable(Table table){
        Map<String,Integer> tableResult=new HashMap<>();
        //默认餐桌上限为100
        for(int i=1;i<100;i++){
            if(tableDao.selectByPrimaryKey(i).getTableNumber().equals(table.getTableNumber())){
                throw new SystemException("餐桌号重复，请重新选择桌号！");
            }else{
                tableResult.put("tableNumber",table.getTableNumber());
                tableResult.put("seats",table.getSeats());
                tableResult.put("status",0);
                tableDao.insertSelective(tableResult);
            }
        }
        return table.getId();
    }

    @Override
    //更新餐桌信息
    public void updateTableStatus(int tableNumber, boolean occupied){
        Table table = tableDao.selectByTableNumber(tableNumber);
        if (table == null) {
            throw new SystemException("该桌子不存在");
        }
        table.setStatus(occupied? 1 : 0);
        tableDao.updateByPrimaryKeySelective(table);
    }

    @Override
    //删除餐桌
    public void removeTable(int tableId){
        //判断餐桌状态是否空闲
        if(tableDao.selectByPrimaryKey(tableId).getStatus().equals(1)){
            throw new SystemException("餐桌使用中，暂时无法删除！");
        }else{
            tableDao.deleteByPrimaryKey(tableId);
        }

    }

    @Override
    public List<Table> selectTable() {
        List<Table> tables = tableDao.selectAll();
        return tables;
    }
}
